<template>
	<div class="table-demo-container layout-padding">
		<el-row>
			<el-col :xs="24" :sm="24">
				<el-card shadow="hover" header="实验检索">
					<TableSearch
						:search="state.search"
						@search="onSearch"
						v-loading.fullscreen.lock="fullscreenLoading"
						:element-loading-text="'数据加载中,请稍后...'"
					/>
				</el-card>
			</el-col>
			<el-col :xs="14" :sm="14">
				<el-card shadow="hover" header="柱形图" class="card-height">
					<div v-show="state.data.length == 0" class="empty">
						<el-empty description="暂无数据" />
					</div>
					<div v-show="state.data.length != 0" class="flex-warp-item">
						<div class="flex-title">
							<span>学生成绩分布情况</span>
							<span class="flex-title-small">单位: 人</span>
						</div>
						<div class="flex-content">
							<div style="width: 700px; height: 200px;" ref="columnChartsRef"></div>
						</div>
					</div>
				</el-card>
				<el-card shadow="hover" header="折线图" class="card-height">
					<div v-show="state.data.length == 0" class="empty">
						<el-empty description="暂无数据" />
					</div>
					<div v-show="state.data.length != 0" class="flex-warp-item">
						<div class="flex-title">
							<span>学生成绩分布情况</span>
							<span class="flex-title-small">单位: 人</span>
						</div>
						<div class="flex-content">
							<div style="width: 700px; height: 200px;" ref="lineChartsRef"></div>
						</div>
					</div>
				</el-card>
			</el-col>
			<el-col :xs="10" :sm="10" style="flex: float">
				<el-card shadow="hover" header="饼形图" class="card-right-height">
					<div v-show="state.pieData.length == 0" class="empty">
						<el-empty description="暂无数据" :image-size="300" />
					</div>
					<div v-show="state.pieData.length != 0" class="flex-warp-item">
						<div class="flex-title">
							<span>学生成绩分布情况</span>
							<span class="flex-title-small">单位: 人</span>
						</div>
						<div class="flex-pie-content">
							<div style="width: 750px; height: 750px;margin-left: -125px;margin-top: -100px;" ref="pieChartsRef"></div>
						</div>
					</div>
				</el-card>
			</el-col>
		</el-row>
	</div>
</template>

<script setup lang="ts" name="experimentsManagement">
import { defineAsyncComponent, reactive, ref, onMounted, nextTick, watch, onActivated } from 'vue';
import * as echarts from 'echarts';
import { useTagsViewRoutes } from '/@/stores/tagsViewRoutes';
import { storeToRefs } from 'pinia';
const storesTagsViewRoutes = useTagsViewRoutes();
const { isTagsViewCurrenFull } = storeToRefs(storesTagsViewRoutes);
import { ElMessage } from 'element-plus';
import { lessonInfo, studentGradeInfo, teacherGradeInfo, totalGradeInfo } from '/@/api/grade';

// 引入组件
const TableSearch = defineAsyncComponent(() => import('/@/views/grade/statistics/search.vue'));

// 定义变量内容
const fullscreenLoading = ref(false);
const columnChartsRef = ref();
const pieChartsRef = ref();
const lineChartsRef = ref();
const stateGraph = reactive({
	myCharts: [] as EmptyArrayType,
});
const state = reactive({
	// 搜索表单，动态生成（传空数组时，将不显示搜索，注意格式）
	search: [
		{ label: '实验编号', prop: 'id', placeholder: '请输入想查询的实验编号', required: true, type: 'input' },
		{ label: '实验名称', prop: 'name', placeholder: '请输入想查询的实验名称', required: false, type: 'input' },
		{ label: '班级', prop: 'class', placeholder: '请输入班级', required: false, type: 'select', options: [] },
	],
	grade: [],
	data: [],
	pieData: [],
});

// 柱形图
const initColumnCharts = () => {
	const myChart = echarts.init(columnChartsRef.value, 'dark');
	const option = {
		grid: {
			top: 15,
			right: 15,
			bottom: 25,
			left: 30,
		},
		tooltip: {
			trigger: 'axis',
		},
		xAxis: {
			type: 'category',
			data: ['不及格', '及格', '中等', '良好', '优秀'],
		},
		yAxis: {
			type: 'value',
		},
		series: [
			{
				data: state.data,
				type: 'bar',
			},
		],
	};
	myChart.setOption(option);
	stateGraph.myCharts.push(myChart);
};

//折线图
const initLineCharts = () => {
	const myChart = echarts.init(lineChartsRef.value);
	const option = {
		grid: {
			top: 15,
			right: 15,
			bottom: 25,
			left: 30,
		},
		tooltip: {
			trigger: 'axis',
		},
		xAxis: {
			type: 'category',
			boundaryGap: false,
			data: ['不及格', '及格', '中等', '良好', '优秀'],
		},
		yAxis: {
			type: 'value',
		},
		series: [
			{
				data: state.data,
				type: 'line',
			},
		],
	};
	myChart.setOption(option);
	stateGraph.myCharts.push(myChart);
};

//饼状图
const initPieCharts = () => {
	const myChart = echarts.init(pieChartsRef.value);
	const option = {
		grid: {
			top: 20,
			right: 10,
			bottom: 10,
			left: 5,
		},
		tooltip: {
			trigger: 'item',
		},
		series: [
			{
				name: '学生成绩',
				type: 'pie',
				radius: [50, 150],
				center: ['50%', '50%'],
				roseType: 'area',
				itemStyle: {
					borderRadius: 8,
				},
				data: state.pieData,
			},
		],
	};
	myChart.setOption(option);
	stateGraph.myCharts.push(myChart);
};

// 批量设置 echarts resize
const initEchartsResizeFun = () => {
	nextTick(() => {
		for (let i = 0; i < stateGraph.myCharts.length; i++) {
			stateGraph.myCharts[i].resize();
		}
	});
};
// 批量设置 echarts resize
const initEchartsResize = () => {
	window.addEventListener('resize', initEchartsResizeFun);
};

const onSearch = (data: any) => {
	fullscreenLoading.value = true;
	setTimeout(() => {
		teacherGradeInfo({ experiment_id: data.id })
			.then((res) => {
				if (res.code === '2000') {
					let teacher = res.data.some((item) => item.teacher_grade === -1);
					if (teacher) {
						ElMessage.warning('该实验评分尚未完成,请耐心等待教师评分!');
						fullscreenLoading.value = false;
					} else {
						studentGradeInfo({ experiment_id: data.id })
							.then((result) => {
								if (result.code === '2000') {
									let student = result.data.some((item) => item.evaluated_grade === -1);
									if (student) {
										ElMessage.warning('该实验评分尚未完成,请耐心等待学生评分!');
										fullscreenLoading.value = false;
									} else {
										totalGradeInfo({ experiment_id: data.id })
											.then((response) => {
												if (response.code === '2000') {
													state.grade = response.data.map(item => item.total_grade);
													const failed = state.grade.filter((num) => num < 60).length;
													const passed = state.grade.filter((num) => num >= 60 && num < 70).length;
													const average = state.grade.filter((num) => num >= 70 && num < 80).length;
													const good = state.grade.filter((num) => num >= 80 && num < 90).length;
													const excellent = state.grade.filter((num) => num >= 90 && num <= 100).length;
													state.data = [failed, passed, average, good, excellent];
													state.pieData = [
														{ value: failed, name: '不及格' },
														{ value: passed, name: '及格' },
														{ value: average, name: '中等' },
														{ value: good, name: '良好' },
														{ value: excellent, name: '优秀' },
													];
													initColumnCharts();
													initLineCharts();
													initPieCharts();
													initEchartsResize();
													fullscreenLoading.value = false;
												} else {
													ElMessage.error('获取成绩信息失败!');
													fullscreenLoading.value = false;
												}
											})
											.catch((errors) => {
												ElMessage.error('获取成绩信息失败!' + errors);
												fullscreenLoading.value = false;
											});
									}
								} else {
									ElMessage.error('获取学生成绩信息失败!');
									fullscreenLoading.value = false;
								}
							})
							.catch((error) => {
								ElMessage.error('获取学生成绩信息失败!' + error);
								fullscreenLoading.value = false;
							});
					}
				} else {
					ElMessage.error('获取教师成绩信息失败!');
					fullscreenLoading.value = false;
				}
			})
			.catch((err) => {
				ElMessage.error('获取教师成绩信息失败!' + err);
				fullscreenLoading.value = false;
			});
	}, 2000);
};

onMounted(() => {
	// 获取所有班级信息
	lessonInfo()
		.then((res) => {
			if (res.code === '2000') {
				state.search[2].options = res.data.map((item: any) => {
					return { label: item.lesson_name, value: item.lesson_id };
				});
			} else {
				ElMessage.error('获取班级信息失败!');
			}
		})
		.catch((err) => {
			ElMessage.error('获取班级信息失败!' + err);
		});
});

// 由于页面缓存原因，keep-alive
onActivated(() => {
	initEchartsResizeFun();
});
// 监听 pinia 中的 tagsview 开启全屏变化，重新 resize 图表，防止不出现/大小不变等
watch(
	() => isTagsViewCurrenFull.value,
	() => {
		initEchartsResizeFun();
	}
);
</script>

<style scoped lang="scss">
.table-demo-container {
	overflow: auto;
	.flex-warp-item {
		.flex-title {
			margin-bottom: 10px;
			color: var(--el-text-color-primary);
			display: flex;
			justify-content: space-between;
			.flex-title-small {
				font-size: 12px;
			}
		}
		.flex-content {
			display: flex;
			flex-direction: column;
			height: 200px;
		}
		.flex-pie-content {
			display: flex;
			flex-direction: column;
			height: 500px;
		}
	}
	.card-height {
		margin: 5px;
		height: 320px;
		.empty {
			margin-top: -30px;
		}
	}

	.card-right-height {
		margin: 5px;
		height: 645px;
		.empty {
			margin-top: 30px;
		}
	}
}
</style>
